package com.ftdc.app.lock;

import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class ReadWriteLockExample {
    private final ReadWriteLock lock = new ReentrantReadWriteLock();
    private int sharedData = 0;

    // 读取数据
    public int readData() {
        lock.readLock().lock(); // 获取读锁
        try {
            System.out.println("Reading data: " + sharedData);
            return sharedData;
        } finally {
            lock.readLock().unlock(); // 释放读锁
        }
    }

    // 写入数据
    public void writeData(int newValue) {
        lock.writeLock().lock(); // 获取写锁
        try {
            System.out.println("Writing data: " + newValue);
            this.sharedData = newValue;
        } finally {
            lock.writeLock().unlock(); // 释放写锁
        }
    }

    public static void main(String[] args) {
        ReadWriteLockExample example = new ReadWriteLockExample();

        // 创建读取线程
        Thread reader1 = new Thread(example::readData);
        Thread reader2 = new Thread(example::readData);
        Thread writer = new Thread(() -> example.writeData(42));

        // 启动线程
        reader1.start();
        reader2.start();
        writer.start();

        try {
            reader1.join();
            reader2.join();
            writer.join();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
}
